﻿using System;
using System.Collections.Generic;
using System.Windows.Markup;
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace FireFly
{
    /// <summary>
    /// Warning! this class is not realy tested yet
    /// </summary>
    [Serializable]
    //[DefaultProperty("Bindings")]
    //[ContentProperty("Bindings")]
    public class Events : DependencyObject
    {
        public Events()
        {
        }

        #region DependencyProperty 'Bindings'
        public static void SetBindings(DependencyObject obj, EventHooksCollection hooks)
        {
            obj.SetValue(BindingsProperty, hooks);
            foreach(var hook in hooks)
            {
                hook.SetObject(obj);
            }

            hooks.CollectionChanged += (sender, args) =>
            {
                foreach(EventHook hook in args.OldItems)
                {
                    hook.ClearObject(obj);
                }

                foreach(EventHook hook in args.NewItems)
                {
                    hook.SetObject(obj);
                }
            };
        }

        public static EventHooksCollection GetBindings(DependencyObject obj)
        {
            var list = (EventHooksCollection)obj.GetValue(BindingsProperty);
            if(list == null)
            {
                list = new EventHooksCollection();
                obj.SetValue(BindingsProperty, list);
            }

            return list;
        }

        //[Bindable(true)]
        //[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public static readonly DependencyProperty BindingsProperty = DependencyProperty.RegisterAttached("Bindings",
            typeof(EventHooksCollection), typeof(DependencyObject), new PropertyMetadata(null,
                (target, args) =>
                {
                    if(target == null)
                        return;

                    if(args.OldValue != null)
                    {
                        var hooks = (EventHooksCollection)args.OldValue;
                        foreach(var hook in hooks)
                        {
                            hook.ClearObject(target);
                        }
                    }
                    SetBindings(target, args.NewValue as EventHooksCollection);
                }));
        #endregion
    }

    public class EventHooksCollection : ObservableCollection<EventHook>
    {
    }
}
